<template>
  <div style="display: flex; height: 100%; flex: 1; flex-direction: column">
    <TableWidget ref="refHiDict" :pagination="pagination" :columns="columns" :load="loadData"
                 :has-select="false" :hide-pageable="false" style="flex: 1">
      <template v-slot:toolHeader>
        <TableSearchWidget ref="refSearch" :search="searchItems">
          <template v-slot:searchHead>
            <slot name="searchHead"/>
          </template>
          <template v-slot:searchTail>
            <el-button icon="search" type="success" @click="refresh">
              查询
            </el-button>
            <el-button v-if="addDictLabel" type="primary" icon="Plus" @click="addDict">
              新增字典
            </el-button>
            <el-button v-if="canImport" icon="Download" type="warning" @click="importDict">
              导入
            </el-button>
            <el-button v-if="canExport" icon="Upload" type="danger" @click="exportDict">
              导出
            </el-button>
          </template>
        </TableSearchWidget>
      </template>
      <template v-slot:actionBefore>
        <slot name="actionBefore"/>
      </template>
    </TableWidget>

    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>

    <el-drawer
        v-model="drawer"
        size="50%"
        :title="dictTitle"
        :direction="direction"
        :before-close="handleClose">
      <DictValueList ref="refDictVal" :dict="currentItem"/>
    </el-drawer>

    <ImportDataDialog ref="refImport" url="/uni-center/v1/excel/dict/import"
                      :tips="'是否更新已经存在的字典数据'" :do-upload="uploadAction"/>
  </div>
</template>

<script setup lang="ts">

import {nextTick, onMounted, reactive, ref, computed} from "vue";
import {msgError, msgInfo, msgWarn} from "@/utils/InfoUtil";
import EditDialog from "@/components/common/EditDialog.vue";
import {exportSystemDict, handleResult} from "@/utils/SystemUtil";
import {requestForm} from "@/apis/request";
import {loadSystemDictPage, removeDictClass, saveDictClass} from "@/apis/sop";
import {useStore} from "@/stores";
import TableWidget from "@/widget/TableWidget.vue";
import TableSearchWidget from "@/widget/TableSearchWidget.vue";
import type {DrawerProps} from "element-plus";
import DictValueList from "@/views/sop/list/DictValueList.vue";
import ImportDataDialog from "@/widget/ImportDataDialog.vue";
import {hasMenuPermit} from "@/utils/sop/PermitUtil";
import {filterNameInput} from "@/utils/StrUtil";

withDefaults(defineProps<{
  product?: boolean,
}>(), {});

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const drawer = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const dictTitle = ref('');

const store: any = useStore();
const refImport = ref();
const refHiDict = ref();
const refDictVal = ref();
const refSearch = ref();
const refEditDlg = ref();

const currentItem = ref();

const addDictLabel = computed(() => {
  return hasMenuPermit('asset:dict:add') ? '新增字典' : '';
})

const deleteDict = () => {
  return hasMenuPermit('asset:dict:delete');
}

const editDict = () => {
  return hasMenuPermit('asset:dict:edit');
}

const canImport = computed(() => {
  return hasMenuPermit('asset:dict:import') ? '导入' : '';
})

const canExport = computed(() => {
  return hasMenuPermit('asset:dict:export') ? '导出' : '';
})

const options = [
  {
    value: 0,
    label: '正常'
  },
  {
    value: 1,
    label: '删除'
  },
  {
    value: 2,
    label: '停用'
  }
]

const searchItems = ref([
  {
    type: 'select',
    name: 'state',
    label: '状态',
    size: 'default',
    placeholder: '',
    clearable: true,
    defValue: 0,
    width: '122px',
    options: options
  },
  {
    type: 'input',
    name: 'name',
    label: `名称`,
    size: 'default',
    width: '160px',
    placeholder: `请输入字典类别名称`,
    clearable: true,
    defValue: '',
  },
  {
    type: 'input',
    name: 'code',
    label: `编码`,
    size: 'default',
    width: '160px',
    placeholder: `请输入字典类别编码`,
    clearable: true,
    defValue: '',
  }
]);

const rules = reactive({
  name: [{required: true, message: '请输入字典类别名称', trigger: ['blur']},],
  code: [{required: true, message: '请输入字典类别编码', trigger: ['blur']},],
})

const handleClose = () => {
  drawer.value = false;
}

const onShowDictValue = async () => {
  drawer.value = true;
  await nextTick(() => {
    refDictVal.value.refresh();
  })
}

const importDict = () => {
  refImport.value.handleImport();
}

const exportDict = async () => {
  const platform: any = store.getCurrentPlatform();

  await exportSystemDict({
    platformId: platform.id,
  }, `platform_dict_${new Date().getTime()}.xlsx`, {});
}

const uploadAction = async (option: any, url: any, headers: any) => {
  const platform: any = store.getCurrentPlatform();
  let formData: any = new FormData();
  formData.append("file", option.file);
  formData.append("platformId", platform.id);

  await requestForm({
    url: url,
    method: 'post',
    headers: headers,
    data: formData,
  });
  refresh();
}

const loadData = async (params: any) => {
  const currentPl: any = store.getCurrentPlatform();

  const result = await loadSystemDictPage({
    platformId: currentPl.id,
    name: '',
    ...params
  });

  if (result && result.code === 0) {
    msgInfo('加载字典信息成功!');
    handleResult(result.data, ['$comment']);
  } else {
    msgError(result?.message || '加载字典信息失败！');
  }

  return result;
}

const onSubmit = async (item: Record<string, any>, editType: string) => {
  const currentPl: any = store.getCurrentPlatform();
  item.existUpdate = 'add' == editType ? 0 : 1;
  item.platformId = currentPl.id;

  const result = await saveDictClass(item);
  if (result && result.code === 0) {
    msgInfo('保存字典信息成功!');
    setTimeout(() => refresh(), 300);
  } else {
    msgError(result ? result.message : '保存字典信息失败！');
  }

  return result;
}

const newDict = () => {
  return {
    state: 0,
  };
}

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'name',
    name: '字典类别名称',
    show: true,
    action: (data: any, row: any) => {
      if (row.state == 0) {
        currentItem.value = row;
        dictTitle.value = `字典信息（${row.code}）`
        onShowDictValue()
      } else if (row.state == 1) {
        msgWarn('此字典已删除')
      } else {
        msgWarn('此字典已停用')
      }
    }
  },
  {
    id: 'code',
    name: '类别编码',
    show: true,
    inputCheck: (row: any) => {
      row.code = filterNameInput(row.code);
      if (row.code.length > 64) {
        row.code = row.code.substring(0, 64);
      }
    }
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => {
      return tag == 0 ? 'success' : tag == 1 ? 'danger' : 'warning';
    },
    tagText: (tag: number) => {
      return tag == 0 ? '正常' : tag == 1 ? '删除' : '停用';
    },
    options: options
  },
  {
    id: 'comment',
    name: '描述',
    show: true,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    fixed: 'right',
    canEdit: false,
    operations: [
      {
        name: '编辑',
        iconType: 'primary',
        disabled: (row: any) => {
          return !editDict();
        },
        callback: (data: any, row: any) => {
          currentItem.value = row;
          refEditDlg.value?.editUpdate('编辑字典', row);
        }
      },
      {
        type: 'confirm',
        name: '删除',
        disabled: (row: any) => {
          return row.state != 0 || !deleteDict();
        },
        confirm: async (data: any, row: any) => {
          const result = await removeDictClass({
            platformId: row.platformId,
            dictId: row.id,
          });
          if (result.code === 0) {
            msgInfo('删除字典成功！');
            refresh();
          } else {
            msgError(result.message ? result.message : '删除字典失败！');
          }
        }
      }
    ]
  }
]);

const addDict = () => {
  currentItem.value = newDict();
  refEditDlg.value?.editAdd('新增字典', currentItem.value);
}

onMounted(() => {

})

const doRefresh = async (params: any) => {
  await refHiDict.value?.refreshData({
    ...params,
    ...refSearch.value?.getSearchParams()
  });
}

const refresh = () => {
  doRefresh({});
}

defineExpose({
  refresh,
})
</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
